package cn.sumpu.app.guoguojie.biz.impl;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import cn.sumpu.app.guoguojie.biz.*;
import cn.sumpu.app.guoguojie.constant.Grid;
import cn.sumpu.app.guoguojie.constant.SearchType;
import cn.sumpu.app.guoguojie.dao.*;
import cn.sumpu.app.guoguojie.domain.*;
import cn.sumpu.app.guoguojie.exception.*;
import cn.sumpu.app.guoguojie.util.*;

public class DoingTagShowBizImpl implements DoingTagShowBiz {

	@Resource
	private IdentifierBiz identifierBiz;
	@Resource
    private FastextBiz fastextBiz;

	private DoingTagShowDao doingTagShowDao;

	public void setDoingTagShowDao(DoingTagShowDao doingTagShowDao) {
		this.doingTagShowDao = doingTagShowDao;
	}

	/**
	 * author BruceZhang
	 * 
	 * @param doingTagShow
	 *            添加前台标签
	 * @throws AppBusinessException
	 */
	@Override
	public void addDoingTagShow(DoingTagShow doingTagShow)
			throws AppBusinessException {
		doingTagShow.setIdentifier(identifierBiz.generateId("doing_tag_show"));
		doingTagShowDao.addDoingTagShow(doingTagShow);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param doingTagShow
	 *            更改前台标签
	 * @throws AppBusinessException
	 */
	@Override
	public void updateDoingTagShow(DoingTagShow doingTagShow)
			throws AppBusinessException {
		doingTagShowDao.updateDoingTagShow(doingTagShow);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            父节点ID（parentIdentifier）
	 * @return 这个父节点下的所有标签
	 * @throws AppBusinessException
	 */
	@Override
	public List<DoingTagShow> getDoingTagShow(String parentIdentifier)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentIdentifier", parentIdentifier);
		return doingTagShowDao.getDoingTagShow(map);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            父节点ID（parentIdentifier）
	 * @return 根据父ID取得字节点
	 * @throws AppBusinessException
	 */
	@Override
	public List<DoingTagShow> getDstByParentId(String parentId)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentIdentifier", parentId);
		return doingTagShowDao.getDstByParentId(map);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param id
	 *            前台标签ID
	 * @return 一个标签实体
	 * @throws AppBusinessException
	 */
	@Override
	public DoingTagShow getDstById(String id) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		return doingTagShowDao.getDstById(map);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            id 删除前台标签
	 * @throws AppBusinessException
	 */
	@Override
	public void deleteDoingTagShow(String ids) throws AppBusinessException {
		if (Common.emptyStr(ids) || !"(".equals(ids.substring(0, 1))) {
			ids = "('" + ids + "')";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ids", ids);
		doingTagShowDao.deleteDoingTagShow(map);
	}

	@Override
	public void deleteDoingTagShowAll(String id) throws AppBusinessException {
		// 取得全部子节点（包括自己）
		String identifierList = getChildrenCategoryId(id);
		deleteDoingTagShow(identifierList);
	}

	private String getChildrenCategoryId(String parentId)
			throws AppBusinessException {
		List<String> categoryBuilder = new ArrayList<String>();
		return "(" + getCategory(parentId, categoryBuilder) + ")";
	}

	private String getCategory(String id, List<String> list)
			throws AppBusinessException {
		List<DoingTagShow> cList = buildChildren(id);
		for (DoingTagShow tmp : cList) {
			list.add("'" + tmp.getIdentifier() + "'");
			List<DoingTagShow> children = tmp.getTagList();
			if (null != children && children.size() > 0) {
				getCategory(tmp.getIdentifier(), list);
			}
		}
		StringBuilder s = new StringBuilder();
		for (String tmp : list) {
			s.append(tmp + ",");
		}
		s.append("'" + id + "'");
		return s.toString();
	}

	private List<DoingTagShow> buildChildren(String parentId)
			throws AppBusinessException {
		return getChildrenDoingTagList(parentId);
	}

	private List<DoingTagShow> getChildrenDoingTagList(String parentId)
			throws AppBusinessException {
		List<DoingTagShow> list = getDstByParentId(parentId);
		for (DoingTagShow c : list) {
			c.setTagList(getChildrenDoingTagList(c.getIdentifier()));
		}
		return list;
	}

	// 取得子标签的来源
	@Override
	public String getChildrenBackTag(String parentId)
			throws AppBusinessException {
		return get1(parentId);
	}

	private String get1(String parentId)
			throws AppBusinessException {
		List<String> categoryBuilder = new ArrayList<String>();
		return "(" + build2(parentId, categoryBuilder) + ")";
	}

	private String build2(String id, List<String> list)
			throws AppBusinessException {
		List<DoingTagShow> cList = build3(id);
		for (DoingTagShow tmp : cList) {
			if(tmp.getType()==1){
				list.add("'" + tmp.getBackTag() + "'");
			}
			List<DoingTagShow> children = tmp.getTagList();
			if (null != children && children.size() > 0) {
				build2(tmp.getIdentifier(), list);
			}
		}
		StringBuilder s = new StringBuilder();
		for (String tmp : list) {
			s.append(tmp + ",");
		}
		s.append("'" + id + "'");
		return s.toString();
	}

	private List<DoingTagShow> build3(String parentId)
			throws AppBusinessException {
		return get4(parentId);
	}

	private List<DoingTagShow> get4(String parentId)
			throws AppBusinessException {
		List<DoingTagShow> list = getDstByParentId(parentId);
		for (DoingTagShow c : list) {
			c.setTagList(get4(c.getIdentifier()));
		}
		return list;
	}
	
	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            条件：标签/价格
	 * @return 查询格子屋
	 * @throws AppBusinessException
	 */
	@Override
	public PageModel getGridByCondition(String channel, String pdId, String tagId, Integer minPrice,
	                                    Integer maxPrice, Integer page, Integer times,String mobileMove,String currentDoingId)
			throws AppBusinessException { 
		int allTimes = 10; // 一页分多少次取
		int pageSize = 120; // 一页显示多少条
		if (page == null || page <= 0) {
			page = 1; 
		}
		if (times == null || times <= 0) {
			times = 1;
		}
		PageModel pm = new PageModel();
		
		if(StringUtils.isEmpty(pdId)){
		    return pm;
		}
		Map<String, Object> map = new HashMap<String, Object>();
	//	map.put("pdId", pdId);
		map.put("channel", channel); 
	//	map.put("tag", tagId);
		map.put("minPrice", minPrice);
		map.put("maxPrice", maxPrice);
		
		String pIds = getIndesPids(pdId, tagId);
		map.put("pIds", pIds);
		
		map.put("mobileMove", mobileMove);
        map.put("currentDoingId", currentDoingId);
        
		int count = 0;
		if(StringUtils.isEmpty(mobileMove) && !StringUtils.isEmpty(pIds)){
		    count = getGridCount(channel, pIds,  minPrice, maxPrice);
		    map.put("startId", (page - 1) * pageSize + (times - 1)
                * (pageSize / allTimes));
		    map.put("pageSize", pageSize / allTimes);
		}
		
		List<Doing> pList = null; 
		if(!StringUtils.isEmpty(pIds)){
		    pList = doingTagShowDao.getGridByCondition(map);
		}
		pm.setCurrentPage(page); 
		pm.setList(pList);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize - 1) / pageSize);
		return pm;
	} 
	
	/**
	 * @param pdId 频道ID
	 * @param tagId 标签ID
	 * @return
	 * @throws AppBusinessException
	 */
	public String getIndesPids(String pdId,String tagId)throws AppBusinessException{
	    if(StringUtils.isEmpty(pdId)) return "('')";
	    List<Map<String,Object>> indexList = new ArrayList<Map<String,Object>>();
        String pTagId = Grid.getShow(pdId);
        DoingTagShow pTagShow = getDstById(pTagId);
        if(pTagShow != null){
            Map<String,Object> pTagMap = new HashMap<String,Object>();
            pTagMap.put("keywords", pTagShow.getKeywords());
            pTagMap.put("isPart", false);
            indexList.add(pTagMap);
        }
        if(!StringUtils.isEmpty(tagId)){ 
            DoingTagShow tagShow = getDstById(tagId);
            if(tagShow != null){
                Map<String,Object> tagMap = new HashMap<String,Object>();
                tagMap.put("keywords", tagShow.getKeywords());
                tagMap.put("isPart", false);
                indexList.add(tagMap);
            }
        }
        
        Set<String> indexSet = fastextBiz.search(SearchType.PRODUCT, indexList);
     //   indexSet.add("100009170");
   //     indexSet.add("100009174");
    //    indexSet.add("100009178");
    //    indexSet.add("100009181");
        if(indexSet != null && indexSet.size() > 0){
            StringBuffer sb = new StringBuffer();
            sb.append("(");
            int i = 0;
            for (String string : indexSet) {
                if(i != 0){
                    sb.append(",");
                }
                sb.append("'");
                sb.append(string);
                sb.append("'");
                i++;
            }
            sb.append(")");
            return sb.toString();
        }
        return  "('')";
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            条件：标签/价格
	 * @return 查询格子屋的记录数
	 * @throws AppBusinessException
	 */
	@Override
	public int getGridCount(String channel, String pIds, Integer minPrice, Integer maxPrice) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pIds", pIds);
		map.put("channel", channel);
		map.put("minPrice", minPrice);
		map.put("maxPrice", maxPrice);
		return doingTagShowDao.getGridCount(map);
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            条件：标签/价格/延迟时间
	 * @return 查询格子屋最新
	 * @throws AppBusinessException
	 */
	@Override
	public PageModel getGridNew(String pdId, String tagId, Integer page, Integer times,
			Integer minPrice, Integer maxPrice, String mobileMove,String currentDoingId) throws AppBusinessException {
		// 延迟时间
		Date delayTime = DateUtil.parseDate(Common.getTargetTime("时", 3)); 
		int pageSize = 120; // 一页取多少条 
		int allTimes = 10; // 一页分多少次取

		if (page == null || page <= 0) {
			page = 1;
		}
		if (times == null || times <= 0) {
			times = 1;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		
		
		map.put("delayTime", delayTime);
		map.put("minPrice", minPrice);
		map.put("maxPrice", maxPrice);
		
		String pIds = getIndesPids(pdId, tagId);
        map.put("pIds", pIds); 
        
		map.put("mobileMove", mobileMove);
        map.put("currentDoingId", currentDoingId);
		int count = 0;
        if(StringUtils.isEmpty(mobileMove)){
            count = getGridNewCount(pIds,  delayTime, minPrice, maxPrice);
            map.put("startId", (page - 1) * pageSize + (times - 1)
                * (pageSize / allTimes));
            map.put("pageSize", pageSize / allTimes);
        }
		
		List<Doing> pList = null;
		pList = doingTagShowDao.getGridNew(map);  
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(pList);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize - 1) / pageSize);
		return pm; 
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            条件：标签/价格/延迟时间
	 * @return 查询格子屋最新总记录数
	 * @throws AppBusinessException
	 */
	@Override
	public int getGridNewCount(String pIds, Date delayTime, Integer minPrice,
			Integer maxPrice) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pIds", pIds);
		map.put("delayTime", delayTime);
		map.put("minPrice", minPrice);
		map.put("maxPrice", maxPrice);
		return doingTagShowDao.getGridNewCount(map);
	}
	
	/**
	 * @author BruceZhang
	 * @param spfl			大分类
	 * @param tagId			标签ID
	 * @param type			推荐类型：推荐（commend）/最新（new）
	 * @param page			页码
	 * @param times			一次页码里第几次取
	 * @param minPrice		最小价格
	 * @param maxPrice		最大价格
	 * @param request
	 
	@Override
	public PageModel getGrid(String spfl, String id, String type, Integer page, Integer times, Integer minPrice,
			Integer maxPrice,String mobileMove,String currentDoingId, HttpServletRequest request) {
		try {
		    PageModel pageModel = null; 
		    List<DoingTagShow> tags = null;
		    //取得当前标签的实例
            DoingTagShow tagShow = null;
		    //如果通过按钮进入的
		    if(Grid.containMenuId(id)){
		        String pdId = Grid.getShow(spfl);
	            // 查询标签
	            tags = getDoingTagShow(pdId);
	            tagShow = getDstById(pdId);
	            // 如果是推荐分类 
	            if (Common.emptyStr(type) || "commend".equals(type)) {
	                pageModel = getGridByCondition(Grid.channel, Grid.getBack(spfl), null, minPrice,
	                        maxPrice, page, times,mobileMove,currentDoingId);
	                type = "commend";
	            } else {
	                pageModel = getGridNew(Grid.getBack(spfl), null, page, times, minPrice, maxPrice, mobileMove,currentDoingId);
	                type = "new";
	            }
		    }else{
		        String pdId = Grid.getShow(spfl);  
                // 查询标签
                tags = getDoingTagShow(pdId); 
                tagShow = getDstById(id);
                
                // 如果是推荐分类 
                if (Common.emptyStr(type) || "commend".equals(type)) {
                    pageModel = getGridByCondition(Grid.channel, Grid.getBack(spfl), tagShow.getBackTag(), minPrice,
                            maxPrice, page, times,mobileMove,currentDoingId);
                    type = "commend";
                } else {
                    pageModel = getGridNew(Grid.getBack(spfl), tagShow.getBackTag(), page, times, minPrice, maxPrice, mobileMove,currentDoingId);
                    type = "new";
                }
		    }
			
			request.setAttribute("type", type);
			request.setAttribute("tagShow", tagShow);
			request.setAttribute("tags", tags);
			request.setAttribute("pageModel", pageModel);
			request.setAttribute("spfl", spfl);
			request.setAttribute("minPrice", minPrice);
			request.setAttribute("maxPrice", maxPrice);
			request.setAttribute("pdName", Grid.getName(spfl));
			return pageModel;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	*/
	@Override
    public PageModel getGrid(String spfl, String id, String type, Integer page, Integer times, Integer minPrice,
            Integer maxPrice,String mobileMove,String currentDoingId, HttpServletRequest request) {
        try {
            PageModel pageModel = null; 
            
            //取得当前标签的实例
            DoingTagShow tagShow = null;
            String pdId = Grid.getShow(spfl);
           
            List<DoingTagShow> tags = getDoingTagShow(pdId);
            // 查询标签
            if(StringUtils.isEmpty(id)){
                tagShow = getDstById(pdId);
            }else{
                tagShow = getDstById(id);
            }
            
            // 如果是推荐分类 
            if (Common.emptyStr(type) || "commend".equals(type)) {
                pageModel = getGridByCondition(Grid.channel, spfl, id, minPrice,maxPrice, page, times,mobileMove,currentDoingId);
                type = "commend";
            } else {
                pageModel = getGridNew(spfl, id, page, times, minPrice, maxPrice, mobileMove,currentDoingId);
                type = "new";
            }
            
            request.setAttribute("type", type);
            request.setAttribute("tagShow", tagShow);
            request.setAttribute("tags", tags);
            request.setAttribute("pageModel", pageModel);
            request.setAttribute("spfl", spfl);
            request.setAttribute("minPrice", minPrice);
            request.setAttribute("maxPrice", maxPrice);
            request.setAttribute("pdName", Grid.getName(spfl));
            return pageModel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	@Override
	public void getGridBruce(Integer size, HttpServletRequest request) {
		try{
			if(size==null || size<0){
				size = 100;
			}
			List<Doing> list = doingTagShowDao.getGridBruce(size);
			request.setAttribute("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    /**
     * author BruceZhang
     * @param doingId  微博ID
     * @return 查询微博的标签
     * @throws AppBusinessException
     */
    @Override
    public List<String> getTagByDoing(String doingId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("doing", doingId);
        return doingTagShowDao.getTagByDoing(map);
    }

    //通过标签集合查询产品
    @Override
    public PageModel getProductByTags(String tags) throws AppBusinessException {
        if("('')".equals(tags)){
            return new PageModel();
        }
        int pageSize = 30;
        int page = 1;
        Integer count = getDoingCountByTags(tags);
        int pageCount = (count + pageSize - 1) / pageSize;
        page = new Random().nextInt(pageCount) + 1;
        PageModel pm = new PageModel();
        List<Doing> pList = getDoingByTags(tags, page);
        pm.setList(pList);
        return pm;
    }

    /**
     * author BruceZhang
     * @param tags      标签的集合
     * @return 通过标签集合查询微博
     * @throws AppBusinessException
     */
    @Override
    public List<Doing> getDoingByTags(String tags, Integer page) throws AppBusinessException {
        int pageSize = 30;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tags", tags);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        return doingTagShowDao.getDoingByTags(map);
    }

    /**
     * author BruceZhang
     * @param  tags      标签的集合
     * @return 通过标签集合查询微博总数
     * @throws AppBusinessException
     */
    @Override
    public Integer getDoingCountByTags(String tags) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tags", tags);
        return doingTagShowDao.getDoingCountByTags(map);
    }

    /**
     * author BruceZhang
     * @param map  member:会员ID
     * @return 查询我的分享
     * @throws AppBusinessException
     */
    @Override
    public PageModel getDoingByMember(String member, Integer page) throws AppBusinessException {
        if(page == null || page<1){ 
            page = 1;
        }
        int pageSize = 30;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("member", member);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Doing> doingList = doingTagShowDao.getDoingByMember(map);
        Integer count = getDoingCountByMember(member);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(doingList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }
    /**
     * author BruceZhang
     * @param map  member:会员ID
     * @return 查询我的分享总数
     * @throws AppBusinessException
     */
    @Override
    public Integer getDoingCountByMember(String member) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("member", member);
        return doingTagShowDao.getDoingCountByMember(map);
    }

    /**
     * author BruceZhang
     * @param map  member:会员ID
     * @return 查询我的收藏
     * @throws AppBusinessException
     */
    @Override
    public PageModel getDlByMember(String member, Integer page) throws AppBusinessException {
        if(page == null || page<1){
            page = 1;
        }
        int pageSize = 30;  
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("member", member);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Doing> doingList = doingTagShowDao.getDlByMember(map);
        Integer count = getDlCountByMember(member); 
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(doingList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }
    /**
     * author BruceZhang
     * @param map  member:会员ID
     * @return 查询我的收藏总数
     * @throws AppBusinessException
     */
    @Override
    public Integer getDlCountByMember(String member) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>(); 
        map.put("member", member);
        int num=doingTagShowDao.getDlCountByMember(map);
        return num;
    }
    /**
     * author BruceZhang
     * @param map
     * @return 查询话题微博
     * @throws AppBusinessException
     */
    @Override
    public PageModel getDoingByDiscuss(String discussId, Integer page) throws AppBusinessException {
        if(page == null || page<1){
            page = 1;
        }
        int pageSize = 30;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("discussId", discussId);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Doing> doingList = doingTagShowDao.getDoingByDiscuss(map);
        Integer count = getDoingCountByDiscuss(discussId);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(doingList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }
    /**
     * author BruceZhang
     * @param map  member:会员ID
     * @return 查询话题微博总数
     * @throws AppBusinessException
     */
    @Override
    public Integer getDoingCountByDiscuss(String discussId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("discussId", discussId);
        return doingTagShowDao.getDoingCountByDiscuss(map);
    }

    /**
     * author BruceZhang
     * @param snick : 卖家昵称
     * @return 查询好店微博
     * @throws AppBusinessException
     */
    @Override
    public PageModel getDoingBySnick(String snick, Integer page) throws AppBusinessException {
        if(page == null || page<1){
            page = 1;
        }
        int pageSize = 10;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("snick", snick);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Doing> doingList = doingTagShowDao.getDoingBySnick(map);
        Integer count = getDoingCountBySnick(snick);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(doingList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }
    /**
     * author BruceZhang
     * @param snick : 卖家昵称
     * @return 查询好店微博总数
     * @throws AppBusinessException
     */
    @Override
    public Integer getDoingCountBySnick(String snick) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("snick", snick);
        return doingTagShowDao.getDoingCountBySnick(map);
    }
   
}
